import sys
import os
import logging
import re
import json
from typing import Dict, List, Any, Optional, Tuple
from decimal import Decimal

# 添加项目根路径到 sys.path
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))

# 导入 MySQLUtil
from shared.utils.MySQLUtil import MySQLUtil

# 设置日志
logger = logging.getLogger(__name__)

def get_各学历_四大经济区域及总体_就业人数及占比分布(
    project_id: int,
    questionnaire_ids: List[int],
    product_code: Optional[str] = None,
    project_code: Optional[str] = None,
    region_code: Optional[str] = None,
    education: Optional[str] = None
) -> Dict[str, Any]:
    """
    各学历，四大经济区域及总体，就业人数及占比分布 - 指标计算函数
    
    ## 指标说明
    该指标用于统计各学历层次（本科、专科、硕士、博士）在四大经济区域（东部、中部、西部、东北）的就业人数分布，
    以及各区域就业人数在总就业人数中的占比。同时提供总体就业人数和占比数据。
    
    ## Args
        project_id (int): 项目ID，用于查询项目配置信息
        questionnaire_ids (List[int]): 问卷ID集合，用于确定数据范围
        product_code (Optional[str]): 产品编码，用于路由到特定计算逻辑
        project_code (Optional[str]): 项目编码，用于路由到特定计算逻辑
        region_code (Optional[str]): 区域编码，用于路由到特定计算逻辑
        education (Optional[str]): 学历筛选条件，可选值为[本科毕业生，专科毕业生，硕士研究生，博士研究生]
        
    ## 示例
    ### 输入
    ```json
    {
        "project_id": 5895,
        "questionnaire_ids": [11158, 11159],
        "education": "博士研究生"
    }
    ```
    
    ### 输出
    ```json
    {
        "success": true,
        "message": "ok",
        "code": 0,
        "result": [
            {
                "name": "东部地区",
                "count": 15,
                "ratio": "15.00%"
            },
            {
                "name": "中部地区",
                "count": 20,
                "ratio": "20.00%"
            },
            {
                "name": "西部地区",
                "count": 50,
                "ratio": "50.00%"
            },
            {
                "name": "东北地区",
                "count": 15,
                "ratio": "15.00%"
            },
            {
                "name": "总体",
                "count": 100,
                "ratio": "100.00%"
            }
        ]
    }
    ```
    """
    logger.info(f"开始计算指标: 各学历，四大经济区域及总体，就业人数及占比分布, 项目ID: {project_id}")
    
    try:
        db = MySQLUtil()  

        # 1. 查询项目配置信息
        project_sql = """
        SELECT client_code, item_year 
        FROM client_item 
        WHERE id = %s
        """
        project_info = db.fetchone(project_sql, (project_id,))
        if not project_info:
            raise ValueError(f"未找到项目ID={project_id}的配置信息")

        client_code = project_info['client_code']
        item_year = project_info['item_year']
        
        logger.info(f"项目配置: client_code={client_code}, item_year={item_year}")

        # 2. 计算 shard_tb_key
        shard_tb_key = re.sub(r'^[A-Za-z]*0*', '', client_code)
        logger.info(f"计算得到 shard_tb_key: {shard_tb_key}")

        # 3. 处理学历参数（空字符串转为None）
        if education == '':
            education = None
        
        # 4. 构建学历筛选条件
        education_condition = ""
        if education:
            valid_educations = ["本科毕业生", "专科毕业生", "硕士研究生", "博士研究生"]
            if education not in valid_educations:
                raise ValueError(f"学历参数必须是以下值之一: {valid_educations}")
            education_condition = f"AND education = '{education}'"
        
        logger.info(f"学历筛选: {education if education else '不限制，返回所有学历明细'}")
        
        # 5. 计算四大区域就业人数及占比
        student_table = f"dim_client_target_baseinfo_student_calc_{item_year}"
        
        # 6. 定义查询函数：查询指定学历的四大区域就业分布
        def query_region_distribution(edu_condition: str, group_name: str) -> List[Dict[str, Any]]:
            """查询指定学历的四大区域就业人数及占比"""
            # 计算总就业人数
            total_sql = f"""
            SELECT count(*) AS total 
            FROM {student_table} 
            WHERE shard_tb_key = %s 
            AND grad_dest_merge NOT IN ('待就业', '暂不就业') 
            AND four_zone != ''
            {edu_condition}
            """
            total_result = db.fetchone(total_sql, (shard_tb_key,))
            if not total_result or total_result['total'] == 0:
                logger.warning(f"分组 '{group_name}': 未找到符合条件的就业数据")
                return []
            
            total_count = int(total_result['total'])
            
            # 查询各区域就业人数
            region_sql = f"""
            SELECT 
                four_zone as region, 
                count(*) as count
            FROM {student_table}
            WHERE shard_tb_key = %s
            AND grad_dest_merge NOT IN ('待就业', '暂不就业')
            AND four_zone != ''
            {edu_condition}
            GROUP BY four_zone
            """
            region_results = db.fetchall(region_sql, (shard_tb_key,))
            
            if not region_results:
                logger.warning(f"分组 '{group_name}': 未找到各区域就业数据")
                return []
            
            # 构建返回结果
            result = []
            for region in region_results:
                region_name = region['region']
                region_count = int(region['count'])
                ratio = Decimal(region_count) / Decimal(total_count) * 100
                result.append({
                    "name": region_name,
                    "count": region_count,
                    "ratio": f"{ratio:.2f}%"
                })
            
            # 添加总体数据
            result.append({
                "name": "总体",
                "count": total_count,
                "ratio": "100.00%"
            })
            
            return result
        
        # 7. 计算各学历和总体数据
        result = []
        
        # 7.1 如果指定了学历，只返回该学历的数据
        if education:
            logger.info(f"开始计算学历 '{education}' 的四大区域就业分布")
            edu_data = query_region_distribution(f"AND education = '{education}'", education)
            if edu_data:
                result.extend(edu_data)
        else:
            # 7.2 如果没有指定学历，返回所有学历的明细数据（按学历分组）
            logger.info("开始计算所有学历的四大区域就业分布明细")
            education_list = ["本科毕业生", "专科毕业生", "硕士研究生", "博士研究生"]
            
            for edu in education_list:
                logger.info(f"计算学历 '{edu}' 的四大区域就业分布")
                edu_data = query_region_distribution(f"AND education = '{edu}'", edu)
                if edu_data:
                    # 按学历分组返回，每个学历的数据作为一个组
                    result.append({
                        "education": edu,
                        "data": edu_data
                    })
        
        # 7.3 计算总体数据（必须包含）
        logger.info("开始计算总体的四大区域就业分布")
        overall_data = query_region_distribution("", "总体")
        if overall_data:
            if education:
                # 如果指定了学历，直接添加总体数据到结果列表
                result.extend(overall_data)
            else:
                # 如果没有指定学历，总体数据也作为一组
                result.append({
                    "education": "总体",
                    "data": overall_data
                })
        
        if not result:
            raise ValueError("未找到任何符合条件的就业数据")
        
        logger.info(f"指标 '各学历，四大经济区域及总体，就业人数及占比分布' 计算成功")
        return {
            "success": True,
            "message": "ok",
            "code": 0,
            "result": result
        }

    except Exception as e:
        logger.error(f"计算指标 '各学历，四大经济区域及总体，就业人数及占比分布' 时发生错误: {str(e)}", exc_info=True)
        return {
            "success": False,
            "message": f"数据获取失败: 各学历，四大经济区域及总体，就业人数及占比分布",
            "code": 500,
            "error": str(e)
        }